
#include "btl_config.h"
#include "fp_spi.h"
#include "fp_util.h"
#include "fp_log.h"
#include "fp_timer.h"

#define IO_SPI_CS_LO 0
#define IO_SPI_CS_HI 1

#define spi2_cs_init()                      \
    do {                                    \
        gpio_set_die(IO_PORTB_11, 1);       \
        gpio_set_direction(IO_PORTB_11, 0); \
        gpio_write(IO_PORTB_11, IO_SPI_CS_LO);         \
    } while (0)

#define spi_cs_h() gpio_write(IO_PORTB_11, IO_SPI_CS_HI)
#define spi_cs_l() gpio_write(IO_PORTB_11, IO_SPI_CS_LO)

static spi_dev spi_handle = SPI2;
const struct spi_platform_data spi2_p_data = {
    .port = 'A',
    .mode = SPI_MODE_BIDIR_1BIT,
    .clk = 12000000, //1000000
    .role = SPI_ROLE_MASTER,
};

void test_spi(void);
void fp_spi_init(void)
{
    spi_open(spi_handle);
    spi2_cs_init();
    // test_spi();
}

void test_spi(void)
{
    unsigned char data[5];
    while (1)
    {
        spi_cs_l();
        delay_count(100);

        spi_send_byte(spi_handle, 0x55);
        bf_print_d("%s write: 0x55", __func__);
        spi_send_byte(spi_handle, 0xaa);
        bf_print_d("%s write: 0xaa", __func__);

        spi_cs_h();
        delay_count(100);

        fp_timer_delay_ms(100);

        spi_cs_l();
        delay_count(100);

        // spi_send_byte(spi_handle, 0x55);
        // bf_print_d("%s write: 0x55", __func__);
        // spi_send_byte(spi_handle, 0xaa);
        // bf_print_d("%s write: 0xaa", __func__);
        fp_spi_receive(data, 5);

        spi_cs_h();
        delay_count(100);
    }
    
}


int fp_spi_send_byte(unsigned char nData)
{
    spi_send_byte(spi_handle, nData);
    return 0;
}

// [put] pData: received data, the buffer is supplied by caller
// [ret] int: 0 - success, other - failed
int fp_spi_receive(uint8_t *pData, unsigned int num)
{
    unsigned int i;
    int err;

    for (i = 0; i < num; i++)
    {
        pData[i] = spi_recv_byte(spi_handle, &err);
        if (err)
            return -1;
    }
    return 0;
}

void fp_spi_cs(unsigned char LEVEL)
{
    if (LEVEL == 0)
        spi_cs_l();
    else
        spi_cs_h();

    delay_count(100);
}

// int fp_spi_write(unsigned char reg, unsigned char value)
// {
//     int i;
//     int retval = -1;
//     uint8_t addr = (reg << 1) | 0x80;
//     uint8_t data[2] = {0};

//     data[0] = addr;
//     data[1] = value;

//     fp_spi_cs(0);

//     for (i = 0; i < LEN_ARRAY(data); ++i)
//     {
//         retval = fp_spi_send_byte(data[i]);
//         if (retval != 0)
//             break;
//     }

//     fp_spi_cs(1);
//     return retval;
// }

// int fp_spi_read(uint8_t reg, uint8_t* data)
// {
//     int retval   = -1;
//     uint8_t addr = (reg << 1) | 0x7f;

//     fp_spi_cs(0);
//     // 1 write addr,
//     retval = fp_spi_send_byte(addr);
//     if (retval != 0)
//         goto ERROR_HANDLE;

//     // 2 write dummy and recv valid data
//     retval = fp_spi_receive(data, 1);

// ERROR_HANDLE:
//     fp_spi_cs(1);
//     return retval;
// }
